package ext.mango.aa.po;

import java.io.IOException;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ext.mango.aa.eo.EOAALoginHistory;
import ext.mango.aa.eo.EOAAUser;
import ext.mango.aa.so.AppManager;
import ext.mango.base.Messages;
import ext.mango.base.POBase;
import ext.mango.functions.Func;
import mango.functions.FuncDate;
import mango.functions.FuncString;
import mango.orm.DaoFactory;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.service.ServiceManager;
import mango.web.Info;

public class Login extends POBase {
    private Log log = LogFactory.getLog(Login.class);

    public boolean dl() {
        String usr = this.getRequestParameter("usr"); //$NON-NLS-1$
        String pwd = this.getRequestParameter("pwd"); //$NON-NLS-1$
        
        String sql = "select * from AAUser where id=? and pwd=?"; //$NON-NLS-1$
        EOAAUser user = (EOAAUser) DaoFactory.c(sql, EOAAUser.class).setParameter(usr,pwd).uniqueResult();
        if (user == null) {
//            this("{success : false, msg: '用户名或密码不正确！'}");
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"userpwderror")); //$NON-NLS-1$
            return false;
        }
        if ("0".equals(user.getAviliable())) { //$NON-NLS-1$
            this.addInfo(Info.ERROR, Messages.getString(user.getLanguage(),"userwaslocked")); //$NON-NLS-1$
            return false;
        }
        ServiceManager.getService(AppManager.class).killSession(user.getId());
        ServiceManager.getService(AppManager.class).onLogin(user.getId(), this.request.getSession());
        this.setCurrentUser(user);
        this.setSessionAttr("theme", Func.getThemeStyle(user)); //$NON-NLS-1$
        EOAALoginHistory history = new EOAALoginHistory();
        history.setId(UUID.randomUUID().toString())
               .setSessionId(this.getRequest().getSession().getId())
               .setUsrId(user.getId())
               .setLoginDate(FuncDate.getCurrentDate())
               .setLoginTime(FuncDate.getCurrentTime())
               .setStatus("1") //$NON-NLS-1$
               .setRemotHost(this.getRequest().getRemoteHost())
               .setUserName(this.getCurrentUser().getUsrName());
        String delSql = "delete from AALoginHistory where usrid=? and status='1'"; //$NON-NLS-1$
        DBSession session = DBSessionFactory.getCurrentSession();
        session.execute(delSql,user.getId());
        session.save(history);
        session.commit();
//        this.addInfo("{success : true, msg: 'Welcome!'}");
        this.addInfo(Info.SUCCESS, "Welcome!"); //$NON-NLS-1$
        return true;
    }

    public boolean tc() {
        if(this.getCurrentUser() == null) {
            return true;
        }
        String usrId = this.getCurrentUser().getId();
        String sessionId = request.getSession().getId();
        ServiceManager.getService(AppManager.class).killSession(usrId);
        DaoFactory.c("update AALoginHistory set logoutDate = ?, logoutTime=?, status=? where  usrId=? and sessionId = ?") //$NON-NLS-1$
                .setParameter(FuncDate.getCurrentDate(), FuncDate.getCurrentTime(),"0", usrId, sessionId)
                .executeUpdate();
        log.debug(Messages.getString(this.getLanguage(),"theuser") + usrId + Messages.getString(this.getLanguage(),"exited")); //$NON-NLS-1$ //$NON-NLS-2$
        String other = this.getRequestParameter("other"); //$NON-NLS-1$
        if (!FuncString.isBlank(other)){
            try {
                this.getResponse().sendRedirect(this.getRequest().getContextPath());
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    
    public void handleException(Exception e) {
        if ("dl".equals(this.method)) { //$NON-NLS-1$
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"loginfailed")); //$NON-NLS-1$
        }
    }
}
